﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Designer.Event.UI;
using CPPEI.Coolzon.Designtime.Metadata;
using CPPEI.Coolzon.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace CPPEI.Coolzon.Designer.Views
{
    public partial class SolutionView
    {
        [Subscribe]
        public void OnSelectPartInstance(UISelectPartInstanceEvent @event)
        {
        }

        [Common.Subscribe]
        public void OnOpenSolution(UIOpenSolutionEvent @event)
        {
            if (!@event.IsSuccess)
            {
                this.Dispatcher.Invoke(() => { CustomMessageBox.ShowError("打开方案失败,错误信息：" + @event.ErrMessage); });
                Logger.ErrorToTag("SolutionView", string.Format("打开方案失败,错误信息：{0}", @event.ErrMessage));
                return;
            }
            if(UIContext.Current.SolutionNode == null)
            {
                Logger.ErrorToTag("SolutionView", string.Format("打开方案失败,错误信息：{0},CurrentSelectedNode为空", @event.ErrMessage));
                return;
            }

            SolutionTreeViewNode tvNode = UIContext.Current.SolutionNode;

            System.Collections.ObjectModel.ObservableCollection<SolutionTreeViewNode> list = new System.Collections.ObjectModel.ObservableCollection<SolutionTreeViewNode>();
            list.Add(tvNode);
            this.Dispatcher.Invoke(() =>
            {
                tvSolution.ItemsSource = list;
                tvNode.IsExpanded = true;
            });

            UIContext.Current.CurrentSolution = @event.Solution;
            UIContext.Current.CurrentDesignView.API_SetSolution(@event.Solution);

            if (@event.OpenTag == 1)
            {
                (UIContext.Current.MainView as MainView).UndoPendingChange();
                this.SelectItem(UIContext.Current.CurrentSelectedNode.ID);
            }
        }

        [Subscribe]
        /// <summary>
        /// 创建场景
        /// </summary>
        /// <param name="sceneMetadata"></param>
        public void OnSceneCreated(UICreateSceneEvent @event)
        {
            try
            {
                if(UIContext.Current.CurrentSelectedNode == null)
                {
                    Logger.Error("SolutionView-OnSceneCreated,创建场景时,错误:未选中节点");
                    return;
                }
                SolutionTreeViewNode parentNode = UIContext.Current.CurrentSelectedNode;

                Scene scene = null;
                if(parentNode.NodeType == NodeType.Resource)
                {
                    Logger.Error("SolutionView-OnSceneCreated,创建场景时,错误:父节点为资源文件");
                    return;
                }
                else
                {
                    if (parentNode.NodeType == NodeType.Scene)
                    {
                        scene = UIContext.Current.CurrentSolution.AddScene(parentNode.FolderID, parentNode.ID, Guid.NewGuid(), @event.Name, @event.Caption, @event.IsShowNavigate, @event.IsAllowSwapArea);
                    }
                    else
                    {
                        scene = UIContext.Current.CurrentSolution.AddScene(parentNode.ID, UIContext.Current.SolutionNode.ID, Guid.NewGuid(), @event.Name, @event.Caption, @event.IsShowNavigate, @event.IsAllowSwapArea);
                    }

                    // 设置场景的宽度
                    CPPEI.Coolzon.UI.XProperty.XPropertyRTUtil.SetPropertyValue<double>(scene.RT_Scene, Scene.SpecialProperty.Width, @event.Width);
                    // 设置场景的高度
                    CPPEI.Coolzon.UI.XProperty.XPropertyRTUtil.SetPropertyValue<double>(scene.RT_Scene,
                        Scene.SpecialProperty.Height, @event.Height);
                }

                SaveScene(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, scene);
                VSFileMgr.GoToAdd(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, scene.ID, scene.FolderId);

                SolutionTreeViewNode sceneNode = SolutionTreeViewNodeConverter.Convert(scene, UpdateStatus);
                this.Dispatcher.Invoke(() =>
                {
                    parentNode.Children.Add(sceneNode);
                    parentNode.IsExpanded = true;
                });

                Logger.Info("SolutionView-OnSceneCreated,创建节点-" + parentNode.Header + " 下场景-" + scene.RT_Scene.Name);
            }
            catch (Exception ex)
            {
                Logger.Error("SolutionView-OnSceneCreated,创建场景时,错误:" + ex.Message);
            }
        }
        [Subscribe]
        public void OnCreateArea(UICreateAreaEvent @event)
        {
        }
        [Subscribe]
        public void OnCreatePart(UICreatePartEvent @event)
        {
        }

        [Subscribe]
        public void OnCreateFolder(UICreateFolderEvent @event)
        {
            if (UIContext.Current.CurrentSelectedNode == null)
            {
                Logger.Error("SolutionView-OnCreateFolder,创建文件夹时,错误:未选中节点");
                return;
            }
            SolutionTreeViewNode parentNode = UIContext.Current.CurrentSelectedNode;

            Designtime.Metadata.Folder folder = UIContext.Current.CurrentSolution.AddFolder(parentNode.ID, Guid.NewGuid(), @event.FolderName);
            SaveSolution(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution);
            VSFileMgr.GoToAdd(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, folder.Id, parentNode.ID);


            SolutionTreeViewNode folderNode = SolutionTreeViewNodeConverter.Convert(folder, UpdateStatus);
            this.Dispatcher.Invoke(() =>
            {
                parentNode.Children.Add(folderNode);
                parentNode.IsExpanded = true;
                folderNode.IsSelected = true;
                folderNode.IsInEditMode = true;
            });


            Logger.Info("SolutionView-OnSceneCreated,创建节点-" + parentNode.Header + " 下文件夹-" + folderNode.Name);
        }

        [Subscribe]
        public void OnAddExisted(UIAddExistedEvent @event)
        {
            if (UIContext.Current.CurrentSelectedNode == null)
            {
                Logger.Error("SolutionView-OnSceneCreated,添加已存在文件时,错误:未选中节点");
                return;
            }
            SolutionTreeViewNode parentNode = UIContext.Current.CurrentSelectedNode;
            parentNode.IsExpanded = true;
            foreach (var file in @event.FileList)
            {
                Guid resourceGuid = Guid.NewGuid();
                Designtime.Metadata.Resource resource = UIContext.Current.CurrentSolution.AddResource(parentNode.ID, resourceGuid, file.FileName, file.Extension);
                SaveResource(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, resourceGuid, file.FullName);
                VSFileMgr.GoToAdd(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, resource.Id, parentNode.FolderID);

                SolutionTreeViewNode resourceNode = SolutionTreeViewNodeConverter.Convert(resource, UpdateStatus);
                this.Dispatcher.Invoke(() =>
                {
                    parentNode.Children.Add(resourceNode);
                });
                Logger.Info("SolutionView-OnSceneCreated,创建节点-" + parentNode.Header + " 下已存在资源文件-" + resourceNode.Name);
            }
        }

        [Subscribe]
        public void OnCreateTemplate(UICreateTemplate @event)
        {
            try
            {

            if (UIContext.Current.CurrentSelectedNode == null)
            {
                Logger.Error("SolutionView-OnCreateTemplate,创建模板时,错误:未选中节点");
                return;
            }
            SolutionTreeViewNode parentNode = UIContext.Current.CurrentSelectedNode;

            if (parentNode.NodeType != NodeType.Scene)
            {
                Logger.Error("SolutionView-OnCreateTemplate,创建模板时,错误:父节点不为场景");
                return;
            }
            Template template = UIContext.Current.CurrentSolution.AddTemplate(parentNode.ID, Guid.NewGuid(), @event.Name, @event.Content);

            Scene scene = SolutionHelper.GetScene(UIContext.Current.CurrentSolution, template.SceneID);
            SaveScene(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, scene);
            VSFileMgr.GoToAdd(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, template.ID, scene.FolderId);

            SolutionTreeViewNode templateNode = SolutionTreeViewNodeConverter.Convert(template, UpdateStatus);
            this.Dispatcher.Invoke(() =>
            {
                parentNode.Children.Add(templateNode);
                parentNode.IsExpanded = true;
            });

            Logger.Info("SolutionView-OnCreateTemplate,创建节点-" + parentNode.Header + " 下模板-" + template.Name);
            }
            catch(Exception ex)
            {
                CustomMessageBox.ShowError(ex.Message);                
                Logger.Info("SolutionView-OnCreateTemplate,创建模板-{0}" + ex);
            }
        }
        [Subscribe]
        public void OnUpdateTemplate(UIUpdateTemplate @event)
        {
            try
            {
                Scene scene = SolutionHelper.GetScene(UIContext.Current.CurrentSolution, @event.SceneID);
                UIContext.Current.CurrentSelectedNode.Header = @event.TemplateName;
                
                scene.UpdateTemplate(@event.TemplateID, @event.TemplateName, @event.Content);
                SaveScene(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, scene);                

                Logger.Info("SolutionView-OnCreateTemplate,更新节点-" + scene.Caption + " 下模板-" + @event.TemplateName);
            }
            catch (Exception ex)
            {
                CustomMessageBox.ShowError(ex.Message);
                Logger.Info("SolutionView-OnCreateTemplate,更新节点-{0}" + ex);
            }
        }

        public void SaveSolution(string workSpacePath, Solution solution)
        {
            LocalStorage.SaveSolutionFile(workSpacePath, solution);
        }

        public void SaveScene(string workSpacepath,Guid solutionID, Scene scene)
        {
            LocalStorage.SaveSceneFile(workSpacepath, solutionID, scene);
            SaveSolution(workSpacepath, UIContext.Current.CurrentSolution);
        }

        public void SaveFolder(string workSpacePath, Solution solution)
        {
            SaveSolution(workSpacePath, solution);
        }

        public void SaveResource(string workSpacepath, Guid solutionId, Guid resourceId, string sourceFilePath)
        {
            LocalStorage.SaveResourceFile(workSpacepath, solutionId, resourceId, sourceFilePath);
            SaveSolution(workSpacepath, UIContext.Current.CurrentSolution);
        }
        
        public void UpdateStatus(SolutionTreeViewNode node)
        {
            VSFile vsFile = VSFileMgr.GetFileWithDefault(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, node.ID);
            if (vsFile != null)
            {
                if (vsFile.Status == VSFileStatus.IsEditing)
                {
                    switch (vsFile.Action)
                    {
                        case VSFileAction.None:
                        case VSFileAction.Move:
                        case VSFileAction.Edit:
                            node.NodeStatus = NodeStatus.CheckOut;
                            break;
                        case VSFileAction.Add:
                            node.NodeStatus = NodeStatus.Add;
                            break;
                        case VSFileAction.Delete:
                            node.NodeStatus = NodeStatus.Delete;
                            break;
                    }
                }
                else if (vsFile.Status == VSFileStatus.IsLocking)
                {
                    node.NodeStatus = NodeStatus.OthersLocked;
                }
                else
                {
                    node.NodeStatus = NodeStatus.CheckIn;
                }
            }
            else
            {
                node.NodeStatus = NodeStatus.NotInSourceControl;
            }
        }

        [Subscribe]
        /// <summary>
        /// 创建静态数据源
        /// </summary>
        /// <param name="sceneMetadata"></param>
        public void OnStaticDataSourceCreated(UICreateStaticDataSourceEvent @event)
        {
            try
            {
                SolutionTreeViewNode parentNode = SolutionTreeViewNodeHelper.GetStaticDataSourceFolderNode();
                if (parentNode == null)
                {
                    Logger.Error("SolutionView-OnStaticDataSourceCreated,创建静态数据源时,错误:无数据源文件夹节点");
                    return;
                }

                Designtime.Metadata.StaticDataSource staticDataSource = new StaticDataSource(parentNode.ID, Guid.NewGuid(), @event.Name);
                staticDataSource.Content = @event.Content;
                UIContext.Current.CurrentSolution.AddStaticDataSource(staticDataSource);

                CPPEI.Coolzon.UI.DataTask.StaticDataSourceManager.SaveDataToFile(@event.Content, Designtime.Metadata.LocalStorage.GetStaticDataSourceAbsolutePath(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, staticDataSource.Id));
                VSFileMgr.GoToAdd(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, staticDataSource.Id, staticDataSource.FolderId);
                SaveSolution(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution);

                SolutionTreeViewNode sceneNode = SolutionTreeViewNodeConverter.Convert(staticDataSource, UpdateStatus);
                this.Dispatcher.Invoke(() =>
                {
                    parentNode.Children.Add(sceneNode);
                    parentNode.IsExpanded = true;
                });

                Logger.Info("SolutionView-OnStaticDataSourceCreated,创建节点-" + parentNode.Header + " 下静态数据员-" + @event.Name);
            }
            catch (Exception ex)
            {
                Logger.Error("SolutionView-OnStaticDataSourceCreated,创建静态数据源时,错误:" + ex.Message);
            }
        }
        [Subscribe]
        /// <summary>
        /// 更新静态数据源
        /// </summary>
        /// <param name="sceneMetadata"></param>
        public void OnStaticDataSourceUpdated(UIUpdateStaticDataSourceEvent @event)
        {
            try
            {
                SolutionTreeViewNode parentNode = SolutionTreeViewNodeHelper.GetStaticDataSourceFolderNode();
                if (parentNode == null)
                {
                    Logger.Error("SolutionView-OnStaticDataSourceUpdated,创建静态数据源时,错误:无数据源文件夹节点");
                    return;
                }
                StaticDataSource staticDataSource = SolutionHelper.GetStaticDataSource(UIContext.Current.CurrentSolution, @event.StaticDataSourceId);
                staticDataSource.Name = @event.Name;
                staticDataSource.Content = @event.Content;

                SolutionTreeViewNode node = SolutionTreeViewNodeHelper.GetStaticDataSourceNode(@event.StaticDataSourceId);
                if(node != null)
                {
                    node.Name = @event.Name;
                    node.Header = @event.Name;
                }

                CPPEI.Coolzon.UI.DataTask.StaticDataSourceManager.SaveDataToFile(@event.Content, Designtime.Metadata.LocalStorage.GetStaticDataSourceAbsolutePath(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, @event.StaticDataSourceId));
                SaveSolution(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution);

                Logger.Info("SolutionView-OnStaticDataSourceUpdated,更新节点-" + parentNode.Header + " 下静态数据员-" + @event.Name);
            }
            catch (Exception ex)
            {
                Logger.Error("SolutionView-OnStaticDataSourceUpdated,更新静态数据源时,错误:" + ex.Message);
            }
        }
    }
}
